package com.yq.day29;

import com.sun.xml.internal.ws.api.pipe.TransportTubeFactory;

import java.util.Random;

/**
 * @author 3307235355@qq.com
 * @description 生产者消费者
 * @since 2022/06/29 11:12
 */
public class Demo06 {
    public static final Object OBJECT = new Object();

    public static void main(String[] args) {

        Box box = new Box();

        ProducerTask p1 = new ProducerTask(box);
        ConsumerTask c1 = new ConsumerTask(box);


        new Thread(p1,"生产者").start();
        new Thread(c1,"消费者").start();

    }

}


class Box {
    Food food;

    //生产包子，只有生产者
    public void setFood(Food newFood) {
        food = newFood;
        System.out.println(Thread.currentThread().getName() + "set" + food);
    }

    //吃包子，消费者
    public void eatFood() {
        System.out.println(Thread.currentThread().getName() + "eat" + food);
        food = null;

    }

    //判断蒸笼的状态
    public boolean isEmpty() {
        return food == null;
    }

}

class Food {
    String name;
    int price;

    public Food(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Food{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}


class ProducerTask implements Runnable{

    Box box;
    Random random = new Random();
    Food[] foods = {new Food("肉包",2),
            new Food("蟹黄包",15),new Food("狗不理",40)};

    public ProducerTask(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            synchronized (box){
                if (box.isEmpty()){
                    int i = random.nextInt(foods.length);
                    box.setFood(foods[i]);
                    box.notify();
                }else {
                    try {
                        box.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                }
            }
        }
    }
}

class ConsumerTask implements Runnable{
    Box box;

    public ConsumerTask(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            synchronized (box){
                if (box.isEmpty()){
                    try {
                        box.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    box.eatFood();
                    box.notify();
                }
            }
        }
    }
}